using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Database;

using Android.Provider;
using System.Collections.Generic;
using FunctionInterface;

namespace Functions
{
	/// <summary>
	/// 查找联系人.
	/// </summary>
	[Activity (Label = "ReadContacts", MainLauncher = true)]
	public class SearchContact : ListActivity, FunctionInterface.IProcessCommand
	{
		public event OutputMessageEventHandler OutputMessage;
		List<string> contactList;
		
		public FunctionInterface.Context Context {get; set;}
		
		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);
		}
		
		public List<string> GetCommnads ()
		{
			List<string> cms = new List<string>();
			cms.Add("-l 获取列表");
			return cms;
			//throw new NotImplementedException ();
		}
		
		public void Process (string command)
		{
			FindContact ();
		}
		
		public bool Validate (string command)
		{
			return true;
		}
		
		public void FindContact()
		{		
			var uri = ContactsContract.Contacts.ContentUri;
            
            string[] projection = 
			{ 
                ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.Contacts.InterfaceConsts.DisplayName 
			};
			ContentResolver resolver = ((Android.Content.Context)Context.MainActivity).ContentResolver;  
			// 获取手机联系人  
			ICursor phoneCursor = resolver.Query(uri, projection, null, null, null);  
			
			contactList = new List<string> ();    

            if (phoneCursor.MoveToFirst ()) 
			{
                do 
				{
                    contactList.Add (phoneCursor.GetString (phoneCursor.GetColumnIndex (projection [1])));
                } while (phoneCursor.MoveToNext());
            }
			
			foreach(string str in contactList)
			{
				if(OutputMessage != null)
				{
					OutputMessage(this, new OutputMessageEventArgs(){ Message = str});
				}
			}
		}
	}
}

